package com.yk.client;

import com.yk.clienthandler.MessageSendHandler;
import com.yk.pool.ClientPool;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by dingkl on 2017/7/28.
 */
public class Loader {
    private EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

    private MessageSendHandler messageSendHandler;

    private static Loader loader;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    private Loader(){}

    public static Loader loader(){
        if (loader==null){
            synchronized (Loader.class){
                if (loader==null){
                    loader = new Loader();
                }
            }
        }
        return loader;
    }

    /**
     * 导入连接
     * @param host
     * @param port
     */
    public void load(String host,int port){
        ClientPool.getExecutorPool();
        RPCClient rpcClient = new RPCClient(eventLoopGroup,host,port,this);
        ClientPool.submit(rpcClient);
    }

    public MessageSendHandler getMessageSendHandler() {
        try {
            lock.lock();
            if (messageSendHandler==null)
                condition.await();
        } catch (InterruptedException e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return messageSendHandler;
    }

    public void setMessageSendHandler(MessageSendHandler messageSendHandler) {
        try {
            lock.lock();
            this.messageSendHandler = messageSendHandler;
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void close(){
        eventLoopGroup.shutdownGracefully();
        ClientPool.close();
    }
}
